package com.wasp.collector.service;

import java.io.IOException;

import org.apache.http.HttpHost;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import com.wasp.collector.data.RequestWrapper;

public class HttpClientCollector{
	private static final int MAXPERROUTE = 20;
	PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
	private int maxRetry = 3;
	private int errorSleepTime = 0;
	private HttpRequestRetryHandler retryHandler = null;
	private CloseableHttpClient httpClient;
	
	public HttpClientCollector(RequestWrapper requestWrapper){
		// Increase max total connection to 200
		cm.setMaxTotal(200);
		// Increase default max connection per route to 20
		cm.setDefaultMaxPerRoute(MAXPERROUTE);
		setRetryHandler(requestWrapper.getErrorSleepTime(),
				requestWrapper.getMaxRetry(),
				requestWrapper.getRetryHandler());
	}
	
	public HttpClientCollector setRouteMax(String host,int port, int maxRoute){
		HttpHost localhost = new HttpHost(host, port);
		cm.setMaxPerRoute(new HttpRoute(localhost), maxRoute);
		return this;
	}
	public HttpClientCollector setRouteMax(String host, int maxRoute){
		setRouteMax(host, 80, maxRoute);
		return this;
	}
	private HttpClientCollector setRetryHandler(int errorSleepTime,
			int maxRetry,
			IRetryHandler handler){
		this.errorSleepTime = errorSleepTime;
		this.maxRetry = maxRetry;
		this.retryHandler = handler == null? 
				new DefaultRetryHandler(errorSleepTime, maxRetry).build()
				: handler.build();
		return this;
	}
	public CloseableHttpClient build(){
		this.retryHandler = this.retryHandler == null? 
				new DefaultRetryHandler(errorSleepTime, maxRetry).build()
				: this.retryHandler;
		httpClient = HttpClients.custom()
		        .setConnectionManager(cm)
		        .setRetryHandler(retryHandler)
		        .build();
		
		return httpClient;
	}
	
	public void destroy(){
		try {
			httpClient.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}